package com.wzu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzu.entity.User;
import com.wzu.mapper.UserMapper;
import com.wzu.service.UserService;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Override
    public User login(String userid, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", userid)
                   .eq("password", password);
        return getOne(queryWrapper);
    }
    
    @Override
    public List<User> getUsersByName(String fullname) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (fullname != null && !fullname.isEmpty()) {
            queryWrapper.like("fullname", fullname);
        }
        return list(queryWrapper);
    }
    
    @Override
    public boolean checkUseridExists(String userid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", userid);
        return count(queryWrapper) > 0;
    }
    
    @Override
    public boolean addUser(User user) {
        // 检查用户账号是否已存在
        if (checkUseridExists(user.getUserid())) {
            return false;
        }
        return save(user);
    }
    
    @Override
    public boolean updateUser(User user) {
        // 检查是否存在其他用户使用相同的userid
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", user.getUserid())
                   .ne("id", user.getId());
        if (count(queryWrapper) > 0) {
            return false;
        }
        return updateById(user);
    }
    
    @Override
    public boolean deleteUser(Integer id) {
        return removeById(id);
    }
}
